<template>
  <div>
    <PageTools>
      <template #before>
        <span>总员工人数: {{ total }} 人</span></template>
      <template #after>
        <el-button
          type="success"
          @click="$router.push('/import')"
        >excel导入</el-button>
        <el-button
          v-arrow="'download'"
          type="info"
          @click="handleDownload"
        >excel导出</el-button>
        <!-- <el-button type="warning">导出zip</el-button> -->
        <el-button type="primary" @click="addEmployees">添加员工</el-button>
      </template>
    </PageTools>
    <el-card>
      <!-- 表格 -->
      <el-table
        :default-sort="{ prop: 'date', order: 'descending' }"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column sortable prop="username" label="姓名" width="120" />
        <el-table-column sortable prop="mobile" label="手机号" width="120" />
        <el-table-column sortable prop="workNumber" label="工号" width="120" />
        <el-table-column sortable label="聘用形式" width="120">
          <template slot-scope="scope">
            {{ formatEmployment(scope.row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="departmentName"
          label="部门"
          width="120"
        />
        <el-table-column sortable label="入职时间" width="120">
          <template slot-scope="scope">
            {{ scope.row.timeOfEntry | formatTimes }}
          </template>
        </el-table-column>
        <el-table-column sortable label="是否在职" width="120">
          <template slot-scope="scope">
            {{ formatWorkingState(scope.row.enableState) }}
          </template>
        </el-table-column>
        <el-table-column sortable label="状态" width="120">
          <template slot-scope="scope">
            {{ scope.row.inServiceStatus == 1 ? '可用' : '不可用' }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="$router.push('/details/' + scope.row.id)"
            >查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button
              type="text"
              size="small"
              @click="assingnRoleClick(scope.row.id)"
            >角色</el-button>
            <el-button
              type="text"
              size="small"
              @click.native="delEmployees(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格 -->

      <!-- 分页 -->
      <el-pagination
        :current-page.sync="paramsObj.page"
        :page-sizes="[1, 3, 5, 7, 10]"
        :page-size="paramsObj.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 对话框 -->
    <el-dialog title="添加新员工" :visible.sync="dialogVisible" width="45%">
      <addEmpDia @success="success" />
    </el-dialog>

    <!-- 分配角色组件 -->
    <el-dialog :visible.sync="showDialogRole" title="分配角色">
      <assign-role
        v-if="showDialogRole"
        :id="id"
        ref="assignRole"
        @closeDialog="showDialogRole = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import addEmpDia from './addEmpDia.vue'
import EmployeeEnum from '@/api/constant/employees'
import { getEmployeeListApi, delEmployeeApi } from '@/api/employees'
import AssignRole from './assignRole.vue'
export default {
  name: '',
  components: { addEmpDia, AssignRole },
  data() {
    return {
      tableData: [],
      paramsObj: {
        page: 1,
        size: 10
      },
      total: 0,
      dialogVisible: false,
      showDialogRole: false,
      id: ''
    }
  },
  computed: {},
  created() {
    this.getEmp() // 获取表格数据
  },
  methods: {
    // 分配角色按钮
    assingnRoleClick(id) {
      this.id = id
      // this.$nextTick(() => {
      //   this.$refs.assignRole.getEmployeeList()
      // })
      this.showDialogRole = true
    },
    // 添加新员工
    addEmployees() {
      this.dialogVisible = true
    },
    // 删除员工
    async delEmployees(id) {
      console.log(this.tableData.length)
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delEmployeeApi(id)
          if (this.tableData.length === 1 && this.paramsObj.page !== 1) {
            this.paramsObj.page--
            this.getEmp() // 获取表格数据
            this.$notify({
              title: '成功',
              message: '删除角色数据成功!',
              type: 'success',
              offset: 200
            })
          } else {
            this.getEmp() // 获取表格数据
            this.$notify({
              title: '成功',
              message: '删除角色数据成功!',
              type: 'success'
            })
          }
        })
        .catch(() => {})
    },
    // 格式化聘用形式
    formatEmployment(num) {
      const { hireType } = EmployeeEnum
      const item = hireType.find((it) => it.id === num)
      if (item) {
        return item.value
      } else {
        return '不能确定'
      }
    },
    // 格式化在职状态形式
    formatWorkingState(num) {
      const { workingState } = EmployeeEnum
      const item = workingState.find((it) => it.id === num)
      if (item) {
        return item.value
      } else {
        return '不能确定'
      }
    },
    handleClick(row) {
      console.log(row)
    },
    // 获取表格数据
    async getEmp() {
      const res = await getEmployeeListApi(this.paramsObj)
      this.tableData = res.data.rows
      // console.log('tableData: ', this.tableData)
      this.total = res.data.total
    },
    /* 分页 */
    handleSizeChange(val) {
      this.paramsObj.size = val
      this.getEmp() // 获取表格数据
    },
    handleCurrentChange(val) {
      this.paramsObj.page = val
      this.getEmp() // 获取表格数据
    },
    // 子组件成功后函数
    success() {
      this.getEmp() // 获取表格数据
      this.dialogVisible = false
    },
    // 导出zip
    // handleDownload1() {
    //   this.downloadLoading = true
    //   import('@/vendor/Export2Excel').then((excel) => {
    //     const multiHeader = [['Id', 'Main Information', '', '', 'Date']]
    //     // const header = ['', 'Title', 'Author', 'Readings', '']
    //     // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
    //     const list = this.tableData
    //     const { headers, data } = this.formatJson(list)
    //     const merges = ['A1:A2', 'B1:D1', 'E1:E2']
    //     excel.export_json_to_excel({
    //       multiHeader,
    //       header: headers,
    //       merges,
    //       data
    //     })
    //     this.downloadLoading = false
    //   })
    // },
    // 导出excel表格
    async handleDownload() {
      const res = await getEmployeeListApi({ page: 1, size: this.total })
      const rows = res.data.rows
      import('@/vendor/Export2Excel').then((excel) => {
        const list = rows
        const { headers, data } = this.formatJson(list)
        excel.export_json_to_excel({
          header: headers,
          data,
          filename: '员工信息',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    formatJson(list) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      var headers = []
      var data = []
      headers = Object.values(map)
      data = list.map((item) => {
        var obj = {}
        const enKey = Object.keys(map)
        enKey.forEach((value) => {
          obj[value] = item[value]
        })
        return Object.values(obj)
      })
      // console.log(data)
      // console.log(headers)
      return { headers, data }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-card {
  margin-top: 15px;
}
.el-pagination {
  text-align: right;
}
</style>
